﻿//-----------------------------------------------------------------------
// <copyright company="Microsoft Corporation">
//     Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Microsoft.DevDiv.Wpf.Samples
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml;
    using System.Xml.XPath;

    internal class LiveSearchXmlObject
    {
        public LiveSearchXmlObject(XPathNavigator navigator, IXmlNamespaceResolver resolver)
        {
            this.navigator = navigator;
            this.resolver = resolver;
        }

        public T GetObject<T>(string xpath, Func<LiveSearchXmlObject, T> create)
        {
            if (this.navigator == null)
            {
                return default(T);
            }

            XPathNavigator node = this.navigator.SelectSingleNode(xpath, this.resolver);
            return create(new LiveSearchXmlObject(node, this.resolver));
        }

        public IEnumerable<T> GetCollection<T>(string xpath, Func<LiveSearchXmlObject, T> create)
        {
            if (this.navigator == null)
            {
                return new T[] { };
            }

            return
                from item in this.navigator.Select(xpath, this.resolver).Cast<XPathNavigator>()
                select create(new LiveSearchXmlObject(item, this.resolver));
        }

        public string GetValue(string xpath)
        {
            if (this.navigator == null)
            {
                return null;
            }

            return this.navigator.SelectSingleNode(xpath, this.resolver).Value;
        }

        public Uri GetValueAsUrl(string xpath)
        {
            string uriString = this.GetValue(xpath);
            return (uriString != null) ? new Uri(uriString, UriKind.Absolute) : null;
        }

        private XPathNavigator navigator;
        private IXmlNamespaceResolver resolver;
    }
}
